package com.hhl.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

	@Value("${server.port}")
	private String PORT;

	@RequestMapping("")
	public String index() {
		return PORT + "HelloWorld";
	}

	@RequestMapping("/setSession")
	public String setSession(HttpServletRequest request, String sessionKey, String sessionValue) {
		// 默认 创建一个session
		HttpSession session = request.getSession(true);
		session.setAttribute(sessionKey, sessionValue);

		System.out.println("存入Session sessionid:信息" + session.getId() + "serverPort:" + PORT);
		return "success,port:" + PORT;
	}

	@RequestMapping("/getSession")
	public String getSession(HttpServletRequest request, String sessionKey) {
		HttpSession session = null;
		try {
			// 设置为true 情况下的时候，客户端使用对应的sessionid 查询不到对应的sesison 会直接创建一个新的session
			// 设置为false 情况下的时候，客户端使用对应的sessionid 查询不到对应的sesison 不 会直接创建一个新的session
			session = request.getSession(false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String value = null;
		if (session != null) {
			value = (String) session.getAttribute(sessionKey);
		}else {
			return PORT + "该服务器上没有存放对应的session值";
		}
		System.out.println("获取Session sessionid:信息" + session.getId() + "serverPort:" + PORT);
		return "sessionValue:" + value + ",port:" + PORT;
	}

}
